package tweetfetch;

import java.sql.*;
import java.util.Date;
import java.util.Random;

public class UserNameQueue {
	Connection conn = null;
	Statement stmt = null;

	public void init_db() throws SQLException {
		conn = DriverManager.getConnection(Console.dbPath);
		stmt = conn.createStatement();
	}

	public void close_db() throws SQLException {
		stmt.close();
		conn.close();
	}

	public String get_one_from_high_queue() {
		String name = null;
		ResultSet rs = null;
		try {
			rs = stmt
					.executeQuery("SELECT * FROM highQueue order by AddTime limit 1;");
			if (rs.next()) {
				name = rs.getString("UserName");
				String query = "delete from highQueue where UserName='" + name
						+ "';";
				int state = stmt.executeUpdate(query);
			}

		} catch (SQLException ex) {
			System.out.println("get one from queue error");
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("ErrorCode: " + ex.getErrorCode());
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException sqlEx) {
				} // ignore
				rs = null;
			}
		}
		return name;
	}

	public String get_one_from_queue() {
		String name = null;
		ResultSet rs = null;
		try {
			rs = stmt
					.executeQuery("SELECT * FROM queue order by AddTime limit 1;");
			if (rs.next()) {
				name = rs.getString("UserName");
				String query = "delete from queue where UserName='" + name
						+ "';";
				int state = stmt.executeUpdate(query);
			}
		} catch (SQLException ex) {
			System.out.println("get one from queue error");
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("ErrorCode: " + ex.getErrorCode());
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException sqlEx) {
				} // ignore
				rs = null;
			}
		}
		return name;
	}

	public void add_to_queue(String username) {
		if (username.equals(""))
			return;
		boolean newInQueue = true;
		ResultSet rs = null;
		try {
			rs = stmt.executeQuery("SELECT * FROM queue where UserName='"
					+ username + "' ;");
			if (rs.next()) {
				newInQueue = false;
			}
		} catch (SQLException ex) {
			System.out.println("get user by username unsuccessful");
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("ErrorCode: " + ex.getErrorCode());
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException sqlEx) {
				} // ignore
				rs = null;
			}
		}
		try {
			if (newInQueue) {
				String query = "INSERT INTO queue VALUES ('" + username + "',"
						+ (new Date()).getTime() / 1000 + ");";
				int state = stmt.executeUpdate(query);
			}
		} catch (SQLException ex) {
			System.out.println("Insert into queue unsuccessful");
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("ErrorCode: " + ex.getErrorCode());
		}
	}
}
